from modules.domain.dept import SysDept
from modules.vo.dept_vo import DeptQueryModel, DeptModel
from modules.schemas.dept_view import SysDeptVo
from tortoise.expressions import Q


class DeptDAO:
    """
    This class is responsible for handling all the database operations related to department.
    """

    @staticmethod
    async def get_dept_list_dao(dept_query: DeptQueryModel):

        query = Q(del_flag="0")

        if dept_query.dept_id is not None:
            query &= Q(dept_id=dept_query.dept_id)
        if dept_query.status is not None:
            query &= Q(status=dept_query.status)
        if dept_query.dept_name is not None:
            query &= Q(dept_name__icontains=dept_query.dept_name)

        data = await SysDept.filter(query).order_by("order_num")
        # print(" = 查询结果 =  ", data, type(data))
        return data

    @classmethod
    async def add_dept_dao(cls, dept_model: DeptModel):
        """
        Add a new department to the database.
        """
        del dept_model.dept_id
        dept = SysDept(**dept_model.model_dump())
        await dept.save()

        await dept.refresh_from_db()
        return dept
